package com.autonavi.yunda.yunji.core.service.dbfactory;

import com.alibaba.lindorm.client.LindormClientConfig;
import com.alibaba.lindorm.client.LindormServiceProvider;
import com.alibaba.lindorm.client.TableService;
import com.alibaba.lindorm.client.exception.LindormException;
import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.core.enums.DBType;
import com.autonavi.yunda.yunji.core.enums.DatasourceType;
import com.autonavi.yunda.yunji.core.service.ILindormTableDBFactory;
import com.autonavi.yunda.yunji.core.vo.datasource.config.LindormDataConfig;
import org.springframework.stereotype.Repository;

import static com.autonavi.yunda.yunji.core.enums.DBType.LINDORM_TABLESERVICE;

/**
 * @author cizhong.wcs
 * @date 2023/5/26 17:14
 */
@Repository
public class LindormTableServiceFactoryService extends AbstractDataSourceFactory<TableService> implements
        ILindormTableDBFactory<TableService> {

    @Override
    public DBType getDbType() {
        return LINDORM_TABLESERVICE;
    }

    @Override
    public TableService createDataSource(DatasourceType dataSourceType, String dataSourceConfig) {
        LindormDataConfig config = JsonUtils.from(dataSourceConfig, LindormDataConfig.class);
        LindormClientConfig clientConfig = new LindormClientConfig();
        clientConfig.setSeedServer(config.getAddress());
        clientConfig.setNamespace(config.getNamespace());
        clientConfig.setUser(config.getUsername(), config.getPassword());
        // 创建lindorm的TableService
        try {
            return LindormServiceProvider.TableServiceProvider.create(clientConfig);
        } catch (LindormException e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "创建 lindormTableService 数据源失败:" + e.getMessage(), e);
        }
    }

    @Override
    public void close(TableService dataSource) {
        if (dataSource == null) {
            return;
        }
        dataSource.close();
    }

    @Override
    public void testConnection(String dataSourceName) {
        try {
            getInstance(dataSourceName);
        } catch (Exception e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, e.getMessage(), e);
        } finally {
            removeDataSource(dataSourceName);
        }
    }
}
